<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import type { Ref } from 'vue'

// 定义 emits
const emit = defineEmits(['createNewApplication'])

// 定义申办资格申请的数据结构
interface QuaApplication {
  quaId: number
  orId: number
  gamesId: number | null
  gamesName: string
  applyMaterials: string
  applyStatus: number
  applyTime: string
  maId: number
  auditOpinion: string
  auditTime: string
}

// 响应式数据
const quaApplications: Ref<QuaApplication[]> = ref([])
const loading: Ref<boolean> = ref(true)
const error: Ref<string | null> = ref(null)
const currentPage: Ref<number> = ref(1)
const pageSize: Ref<number> = ref(2)
const filterStatus: Ref<number | null> = ref(null) // null表示全部

// 获取申办资格审核数据
const fetchQuaApplications = async () => {
  try {
    loading.value = true
    error.value = null
    
    // 从 localStorage 获取 token
    const token = localStorage.getItem('token')
    
    if (!token) {
      throw new Error('未找到身份凭证，请重新登录')
    }
    
    // 发送 GET 请求获取数据
    const response = await fetch('http://localhost:8080/quaApplication/status', {
      method: 'GET',
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      }
    })
    
    const result = await response.json()
    
    if (result.success) {
      quaApplications.value = result.data
    } else {
      throw new Error(result.message || '获取数据失败')
    }
  } catch (err) {
    console.error('获取申办资格审核数据失败:', err)
    error.value = err instanceof Error ? err.message : '获取数据失败'
  } finally {
    loading.value = false
  }
}

// 计算过滤后的数据
const filteredApplications = computed(() => {
  if (filterStatus.value === null) {
    return quaApplications.value
  }
  return quaApplications.value.filter(app => app.applyStatus === filterStatus.value)
})

// 计算当前页的数据
const paginatedApplications = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredApplications.value.slice(start, end)
})

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(filteredApplications.value.length / pageSize.value)
})

// 状态文本映射
const getStatusText = (status: number) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '审核通过'
    case 2: return '审核不通过'
    default: return '未知状态'
  }
}

// 状态样式映射
const getStatusClass = (status: number) => {
  switch (status) {
    case 0: return 'status-pending'
    case 1: return 'status-approved'
    case 2: return 'status-rejected'
    default: return ''
  }
}

// 页面切换
const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

// 筛选状态
const setFilter = (status: number | null) => {
  filterStatus.value = status
  currentPage.value = 1 // 重置到第一页
}

// 新建申办资格
const createNewApplication = () => {
  // 发射事件，通知父组件切换视图
  emit('createNewApplication')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchQuaApplications()
})
</script>

<template>
  <div class="qua-app-container">
    
    <!-- 顶部按钮区域 -->
    <div class="header-buttons">
      <!-- 筛选按钮 -->
      <div class="filter-buttons">
        <button 
          :class="{ active: filterStatus === null }"
          @click="setFilter(null)"
          class="filter-button"
        >
          全部
        </button>
        <button 
          :class="{ active: filterStatus === 0 }"
          @click="setFilter(0)"
          class="filter-button"
        >
          待审核
        </button>
        <button 
          :class="{ active: filterStatus === 1 }"
          @click="setFilter(1)"
          class="filter-button"
        >
          已通过
        </button>
        <button 
          :class="{ active: filterStatus === 2 }"
          @click="setFilter(2)"
          class="filter-button"
        >
          未通过
        </button>
      </div>
      
      <!-- 新建按钮 -->
      <div class="create-button-container">
        <button 
          @click="createNewApplication"
          class="create-button"
        >
          新建申办资格
        </button>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      数据加载中...
    </div>
    
    <!-- 错误状态 -->
    <div v-else-if="error" class="error">
      {{ error }}
    </div>
    
    <!-- 数据展示 -->
    <div v-else class="applications-container">
      <div class="applications-list">
        <div 
          v-for="application in paginatedApplications" 
          :key="application.quaId" 
          class="application-card"
        >
          <div class="card-header">
            <h3>{{ application.gamesName }}</h3>
            <span 
              class="status-badge" 
              :class="getStatusClass(application.applyStatus)"
            >
              {{ getStatusText(application.applyStatus) }}
            </span>
          </div>
          
          <div class="card-body">
            <div class="info-row">
              <span class="label">申请时间:</span>
              <span>{{ new Date(application.applyTime).toLocaleString() }}</span>
            </div>
            
            <div class="info-row">
              <span class="label">审核意见:</span>
              <span>{{ application.auditOpinion }}</span>
            </div>
            
            <div class="info-row">
              <span class="label">审核时间:</span>
              <span>{{ application.applyStatus === 0 ? '' : new Date(application.auditTime).toLocaleString() }}</span>
            </div>
            
            <div class="info-row">
              <span class="label">申请材料:</span>
              <span>{{ application.applyMaterials }}</span>
            </div>
          </div>
        </div>
        
        <!-- 无数据提示 -->
        <div v-if="filteredApplications.length === 0" class="no-data">
          暂无申办资格申请数据
        </div>
      </div>
      
      <!-- 分页控件 -->
      <div v-if="filteredApplications.length > 0" class="pagination">
        <button 
          :disabled="currentPage === 1" 
          @click="goToPage(currentPage - 1)"
          class="page-button"
        >
          上一页
        </button>
        
        <span class="page-info">
          第 {{ currentPage }} 页，共 {{ totalPages }} 页
        </span>
        
        <button 
          :disabled="currentPage === totalPages" 
          @click="goToPage(currentPage + 1)"
          class="page-button"
        >
          下一页
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.qua-app-container {
  width: 95%;
  padding: 20px;
}

.qua-app-container h2 {
  color: #333;
  font-size: 2rem;
  margin-bottom: 20px;
  text-align: center;
}

.header-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.create-button-container {
  flex-shrink: 0;
}

.filter-button {
  padding: 8px 16px;
  background-color: #ecf0f1;
  color: #333;
  border: 1px solid #bdc3c7;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.filter-button:hover {
  background-color: #d6dbdf;
}

.filter-button.active {
  background-color: #3498db;
  color: white;
  border-color: #3498db;
}

.create-button {
  padding: 8px 16px;
  background-color: #27ae60;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.create-button:hover {
  background-color: #219653;
}

.loading, .error, .no-data {
  text-align: center;
  padding: 40px 20px;
  font-size: 1.2rem;
}

.error {
  color: #e74c3c;
}

.no-data {
  color: #7f8c8d;
}

.applications-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.applications-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.application-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.card-header h3 {
  margin: 0;
  color: #333;
}

.status-badge {
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: bold;
}

.status-pending {
  background-color: #f39c12;
  color: white;
}

.status-approved {
  background-color: #27ae60;
  color: white;
}

.status-rejected {
  background-color: #e74c3c;
  color: white;
}

.card-body {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.info-row {
  display: flex;
  flex-wrap: wrap;
}

.label {
  font-weight: bold;
  min-width: 80px;
  margin-right: 10px;
  color: #555;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  padding: 20px 0;
}

.page-button {
  padding: 8px 16px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.page-button:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}

.page-button:hover:not(:disabled) {
  background-color: #2980b9;
}

.page-info {
  font-weight: bold;
  color: #333;
}
</style>